﻿using AutoMapper;
using BasehInfoManager_IDal;
using BasehInfoManagerModel;
using BasehInfoManagerViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using zy_11_10.Common.Lib.TypeTools;

namespace BaseInfoManagerDal
{
  public  class ModuleDbDal:BaseDal, IModuleDbDal
    {
        
        private  IMapper _mapper;
        //注入ef的的上下文
        public ModuleDbDal(ManagerDbContext managerDbContext, IMapper mapper):base(managerDbContext)
        {
           
            _mapper = mapper; 
        }

        //级别显示
        public List<ModuleDb> GetModuleDbsAll()
        {
            return _managerDbContext.ModuleDb.ToList();
        }

        //添加级别
        //首先查找
        public ModuleDb GetModuleDbByModuleCode(string moduleCode)
        {
            return _managerDbContext.ModuleDb.FirstOrDefault(a => a.module_code == moduleCode);
        }

        public bool ModuleAdd(ModuleDb moduleDb)
        {
            _managerDbContext.ModuleDb.Add(moduleDb);
            return _managerDbContext.SaveChanges() > 0;

        }


        //详情
        public ModuleDbView GetModuleDbViewByCode(string moduleCode)
        {
            var view = (from dm in _managerDbContext.ModuleDb
                        join pdm in _managerDbContext.ModuleDb
                        //他要把前面join into 到 leftJoinPdm
                        on dm.parent_code equals pdm.module_code into leftJoinPdm

                        from leftJoinParent in leftJoinPdm.DefaultIfEmpty()
                            //把join查询一下，是否为空，是空就返回空
                        where dm.module_code == moduleCode
                        select new { pname = leftJoinParent.module_name, mdb = dm }).FirstOrDefault();
            if (view == null) return null;
            ModuleDbView mview = _mapper.Map<ModuleDbView>(view.mdb);
            mview.parent_name = view.pname;



            return mview;
        }
        //修改

        public bool ModuleUpdate(ModuleDb moduleDb)
        {
            ModuleDb db = _managerDbContext.ModuleDb.FirstOrDefault(c => c.module_code == moduleDb.module_code);
            ModelCopier.CopyModel(moduleDb, db, "creator_name", "creator_date");
            return _managerDbContext.SaveChanges() > 0;
        }
        //查找
        public ModuleDbView GetModuleDbViewByCodeSonSql(string moduleCode)
        {
            var mdb = _managerDbContext.ModuleDb.FirstOrDefault(a => a.module_code == moduleCode);
            if (mdb == null) return null;
            ModuleDbView mview = _mapper.Map<ModuleDbView>(mdb);
            var p = _managerDbContext.ModuleDb.FirstOrDefault(a => a.module_code == mdb.parent_code);
            mview.parent_name = p != null ? p.module_name : "";
            return mview;
        }

    }

}
